package model

import (
	"encoding/json"
	"onvif_server/internal/model/field"
	"strconv"
)

// Setting 配置表，纪录在数据库，可在线修改生效
type Setting struct {
	Key       string          `gorm:"column:key;type:string;size:100;notNull;primaryKey;default:'';comment:配置key，唯一" json:"key"`
	Val       string          `gorm:"column:val;type:string;notNull;default:'';comment:配置val" json:"val"`
	Sort      int             `gorm:"column:sort;notNull;default:0;comment:排序" json:"sort"`
	Type      string          `gorm:"column:type;type:string;size:100;notNull;default:'';comment:配置val的类型" json:"type"`
	Name      string          `gorm:"column:name;type:string;size:100;notNull;default:'';comment:配置名称" json:"name"`
	Remark    string          `gorm:"column:remark;type:string;size:500;notNull;default:'';comment:配置说明" json:"remark"`
	UpdatedAt field.LocalTime `gorm:"column:updated_at;notNull;comment:最后更新时间" json:"updated_at"`
}

func (m *Setting) ValStrings() ([]string, error) {
	if m.Val == "" {
		return []string{}, nil
	}
	val := make([]string, 0)
	err := json.Unmarshal([]byte(m.Val), &val)
	return val, err
}

func (m *Setting) ValInts() ([]int, error) {
	if m.Val == "" {
		return []int{}, nil
	}
	val := make([]int, 0)
	err := json.Unmarshal([]byte(m.Val), &val)
	return val, err
}

func (m *Setting) ValInt64() (int64, error) {
	if m.Val == "" {
		return 0, nil
	}
	return strconv.ParseInt(m.Val, 10, 64)
}

func (m *Setting) ValInt() (int, error) {
	if m.Val == "" {
		return 0, nil
	}
	i, err := strconv.ParseInt(m.Val, 10, 64)
	return int(i), err
}
